package com.airsystem.pos.bengkel.service;

import java.util.List;

import org.hibernate.Session;

import com.airsystem.pos.bengkel.entity.DetailKendaraan;
import com.airsystem.pos.bengkel.entity.DetailSparepart;
import com.airsystem.pos.bengkel.entity.JenisSparepart;
import com.airsystem.pos.bengkel.interfaces.IParser;
import com.airsystem.pos.bengkel.interfaces.IServices;
import com.airsystem.pos.bengkel.interfaces.IStrategy;
import com.airsystem.pos.bengkel.service.parser.SparepartParser;
import com.airsystem.pos.bengkel.service.strategy.SparepartManyStrategy;
import com.airsystem.pos.bengkel.service.strategy.SparepartOneStrategy;
import com.airsystem.pos.bengkel.util.HibernateUtil;

/**
 * @author Fanny Irawan Sutawanir (fannyirawans@gmail.com)
 */
public class SparepartServices implements IServices<DetailSparepart> {
	private static final StringBuffer SELECT = new StringBuffer("FROM DetailSparepart ").append(DetailSparepart.ALIAS).append(" JOIN detail_sparepart.jenis_sparepart ")
																						.append(JenisSparepart.ALIAS).append(" JOIN detail_sparepart.detail_kendaraan ")
																						.append(DetailKendaraan.ALIAS).append(" WHERE %s LIKE '%s' ORDER BY ")
																						.append(DetailSparepart.ALIAS).append(".sparepart.merk ASC,")
																						.append(DetailSparepart.ALIAS).append(".sub_merk ASC,")
																						.append(DetailKendaraan.ALIAS).append(".kendaraan.merk ASC,")
																						.append(DetailKendaraan.ALIAS).append(".sub_merk ASC,")
																						.append(JenisSparepart.ALIAS).append(".nama ASC");

	private final IParser<List<DetailSparepart>, Iterable<?>> parser;

	private IStrategy strategy;

	public SparepartServices() {
		parser = new SparepartParser();
	}

	/**
	 * Inherit method, Database Action.
	 */
	public void saveOrUpdate(DetailSparepart data) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			session.saveOrUpdate(data.getSparepart());
			session.saveOrUpdate(data);
			session.flush();
		} finally {
			session.close();
		}
	}

	public void delete(DetailSparepart data) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			session.delete(data.getSparepart());
			session.flush();
		} finally {
			session.close();
		}
	}

	public Iterable<DetailSparepart> select(DetailSparepart data) {
		switch (data.getChoice()) {
		case 99: {
			strategy = new SparepartManyStrategy();
			break;
		}

		default: {
			strategy = new SparepartOneStrategy();
			break;
		}
		}

		return strategy.get(data);
	}

	public static String getSelect() {
		return SELECT.toString();
	}

	public IParser<List<DetailSparepart>, Iterable<?>> getParser() {
		return parser;
	}
}